package crp.core.analysis.domain.services;

import crp.core.analysis.domain.commands.CreateViewFlowCommand;
import crp.core.analysis.domain.models.ViewFlowEntity;
import crp.core.analysis.domain.repositories.ViewFlowRepository;
import crp.core.shared.events.EventTopics;
import io.vertx.mutiny.core.eventbus.EventBus;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;

@ApplicationScoped
public class ViewFlowCreator {
    private final ViewFlowRepository viewFlowRepository;
    private final Instance<UserAgentParser> userAgentParser;
    private final Instance<IpInfoLoader> ipInfoLoader;
    private final EventBus eventBus;

    @Inject
    public ViewFlowCreator(ViewFlowRepository viewFlowRepository,
                           Instance<UserAgentParser> userAgentParser,
                           Instance<IpInfoLoader> ipInfoLoader,
                           EventBus eventBus) {
        this.viewFlowRepository = viewFlowRepository;
        this.userAgentParser = userAgentParser;
        this.ipInfoLoader = ipInfoLoader;
        this.eventBus = eventBus;
    }

    public ViewFlowEntity create(CreateViewFlowCommand command) {
        ViewFlowEntity entity = new ViewFlowEntity();
        entity.setTargetType(command.getTargetType());
        entity.setTargetId(command.getTargetId());
        entity.setUserId(command.getUserId());
        entity.setIpInfo(ipInfoLoader.get().load(command.getIp()));
        entity.setUserAgent(userAgentParser.get().parse(command.getUserAgent()));
        viewFlowRepository.persistAndFlush(entity);
        eventBus.publish(EventTopics.VIEW_FLOW_CREATED, entity.getId());
        return entity;
    }
}
